package cn.strongme.security.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * @author Walter
 * @date 2018/7/5 23:41.
 */
@Configuration
@MapperScan("cn.strongme.security.mapper")
@EnableTransactionManagement
@Slf4j
public class MybatisPlusConfig {

    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    @PostConstruct
    public void init() {
        log.info("Init Mybatis Plus");
    }


    @Component
    public class MetaObjectHandlerConfig implements MetaObjectHandler {

        @Override
        public void insertFill(MetaObject metaObject) {
            log.info("Insert Fill");
            Date dateNow = new Date();
            setFieldValByName("createDate", dateNow, metaObject);
            setFieldValByName("updateDate", dateNow, metaObject);
        }

        @Override
        public void updateFill(MetaObject metaObject) {
            log.info("Update Fill");
            Date dateNow = new Date();
            setFieldValByName("updateDate", dateNow, metaObject);
        }
    }

}
